<template>
  <div id="BacDrugResultTempdetail" class="panel-detail">
    <vxe-toolbar perfect>
      <template #buttons>
        <vxe-input type="search" v-model="form.keyvalue" clearable class="vxeInputSearch" @search-click="findList" @clear="findList" @keyup.enter.stop="findList" placeholder="关键字查询"></vxe-input>
        <vxe-button type="text" class="button-blue" @click="findList" icon="vxe-icon-refresh" :loading="loading">刷新</vxe-button>
        <vxe-button type="text" class="button-blue" @click="addBacDrugResultTempdetail" icon="vxe-icon-add">新增</vxe-button>
        <vxe-button type="text" class="button-blue" @click="saveBacDrugResultTempdetail" icon="vxe-icon-save">保存</vxe-button>
        <vxe-button type="text" class="button-red" @click="deleteBacDrugResultTempdetail" icon="vxe-icon-delete">删除</vxe-button>
      </template>
    </vxe-toolbar>
    <div class="tableBox">
      <vxe-table ref="tableRef" border="inner" align="left" class="mytable-scrollbar" resizable :edit-config="{ trigger: 'click', mode: 'cell' }" :loading="loading" height="auto" :data="tableData.filter((data) => !form.keyvalue || (form.keyvalue && ((data.antNa&& data.antNa.includes(form.keyvalue))||(data.antNo&& data.antNo.includes(form.keyvalue)))))" :row-config="{ isCurrent: true }" :column-config="{ resizable: true }" show-overflow keep-source :scroll-y="{ enabled: true }" @current-change="tableCellClick" :menu-config="menuConfig" @menu-click="contextMenuClickEvent">
        <vxe-column type="checkbox" width="26"></vxe-column>
        <vxe-column type="seq" title="#" width="30"></vxe-column>
        <vxe-column field="antPropGroupDictNa" title="抗生素推荐分组" width="110" :edit-render="{ autofocus: '.vxe-input--inner' }">
          <template #edit="{ row, rowIndex }">
            <VxePulldownSelectionWithNa style="width: 100%" :isChild="true" :childIndex="rowIndex" :url="'/api/sys/basDictDetail/findDictDetailList?code=antProposalGroup'" @confirmClick="SelectRowClick" :tableColumn="[
                { field: 'name', title: '名称' },
                { field: 'code', title: '编码' }
              ]" :aimKeys="[
                { aimKey: 'antPropGroupDictNa', rowKey: 'name' },
                { aimKey: 'antPropGroupDictNo', rowKey: 'code' }
                ]" :displayTexts="['antPropGroupDictNa']" :displayTextObj="row.antPropGroupDictNa ? row.antPropGroupDictNa : ''" />
          </template>
        </vxe-column>
        <vxe-column field="antNa" title="抗生素" width="90" :edit-render="{ autofocus: '.vxe-input--inner' }">
          <template #edit="{ row, rowIndex }">
            <VxePulldownSelectionWithNa style="width: 100%" :isChild="true" :childIndex="rowIndex" :url="'/lis/bacAntibioticsDict/findAntDictList'" @confirmClick="SelectRowClick" :tableColumn="[
                { type: 'seq', title: '#', width: '30px' },
                { field: 'antName', title: '名称' },
                { field: 'antCode', title: '编码' }
              ]" :aimKeys="[
                { aimKey: 'antNa', rowKey: 'antName' },
                { aimKey: 'antNo', rowKey: 'antCode' },
                { aimKey: 'antId', rowKey: 'id' }
              ]" :displayTexts="['antNa']" :displayTextObj="row.antNa ? row.antNa : ''" />
          </template>
        </vxe-column>
        <vxe-column field="verificationPrice" title="效价" width="80px" :edit-render="{ autofocus: '.vxe-input--inner' }">
          <template #edit="{ row }">
            <vxe-input v-model="row.verificationPrice" type="text"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="astTestMthDictNa" title="药敏实验方法" width="110px" :edit-render="{ autofocus: '.vxe-input--inner' }">
          <template #edit="{ row, rowIndex }">
            <VxePulldownSelectionWithNa style="width: 100%" :isChild="true" :childIndex="rowIndex" :url="'/lis/bac/base/ast-test-mth/dict/findBacAstTestMthDictList'" @confirmClick="SelectRowClick" :tableColumn="[
                { type: 'seq', title: '#', width: '30px' },
                { field: 'name', title: '名称' },
                { field: 'code', title: '编码' }
              ]" :aimKeys="[
                { aimKey: 'astTestMthDictNa', rowKey: 'name' },
                { aimKey: 'astTestMthDictNo', rowKey: 'code' },
                { aimKey: 'astTestMthDictId', rowKey: 'id' }
              ]" :displayTexts="['astTestMthDictNa']" :displayTextObj="row.astTestMthDictNa ? row.astTestMthDictNa : ''" />
          </template>
        </vxe-column>
        <vxe-column field="interCodeDictNa" title="敏感性" width="80px" :edit-render="{ autofocus: '.vxe-input--inner' }">
          <template #edit="{ row, rowIndex }">
            <VxePulldownSelectionWithNa style="width: 100%" :isChild="true" :childIndex="rowIndex" :url="'/lis/bac/base/interpretation-code/dict/findBacInterpretationCodeDictList'" @confirmClick="SelectRowClick" :tableColumn="[
                { type: 'seq', title: '#', width: '30px' },
                { field: 'name', title: '名称' },
                { field: 'code', title: '编码' }
              ]" :aimKeys="[
                { aimKey: 'interCodeDictNa', rowKey: 'name' },
                { aimKey: 'interCodeDictNo', rowKey: 'code' },
                { aimKey: 'interCodeDictId', rowKey: 'id' }
              ]" :displayTexts="['interCodeDictNa']" :displayTextObj="row.interCodeDictNa ? row.interCodeDictNa : ''" />
          </template>
        </vxe-column>
        <vxe-column field="defResult" title="默认结果" width="100px" :edit-render="{ autofocus: '.vxe-input--inner' }">
          <template #edit="{ row }">
            <vxe-input v-model="row.defResult" type="text"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="breakPoint" title="折点" width="80px" :edit-render="{ autofocus: '.vxe-input--inner' }">
          <template #edit="{ row }">
            <vxe-input v-model="row.breakPoint" type="text"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="r" title="耐药" width="80px" :edit-render="{ autofocus: '.vxe-input--inner' }">
          <template #edit="{ row }">
            <vxe-input v-model="row.r" type="text"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="i" title="中介" width="80px" :edit-render="{ autofocus: '.vxe-input--inner' }">
          <template #edit="{ row }">
            <vxe-input v-model="row.i" type="text"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="sdd" title="剂量依赖型敏感" width="120px" :edit-render="{ autofocus: '.vxe-input--inner' }">
          <template #edit="{ row }">
            <vxe-input v-model="row.sdd" type="text"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="s" title="敏感" width="80px" :edit-render="{ autofocus: '.vxe-input--inner' }">
          <template #edit="{ row }">
            <vxe-input v-model="row.s" type="text"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="ecoff" title="流行病学界值" width="120px" :edit-render="{ autofocus: '.vxe-input--inner' }">
          <template #edit="{ row }">
            <vxe-input v-model="row.ecoff" type="text"></vxe-input>
          </template>
        </vxe-column>
        <!-- <vxe-column field="inputCode" title="助记符" width="90" :edit-render="{ autofocus: '.vxe-input--inner' }">
          <template #edit="{ row }">
            <vxe-input v-model="row.inputCode" type="text"></vxe-input>
          </template>
        </vxe-column> -->
        <vxe-column field="seq" title="排序码" width="90" :edit-render="{ autofocus: '.vxe-input--inner' }">
          <template #edit="{ row }">
            <vxe-input v-model="row.seq" type="text"></vxe-input>
          </template>
        </vxe-column>
      </vxe-table>
    </div>
  </div>
</template>

<script lang="ts" setup>
/**引入组件区 ==========*/
import Breadcrumb from '@/components/Breadcrumb.vue'; /**面包屑*/
import { reactive, ref, getCurrentInstance, onMounted } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import { VXETable } from 'vxe-table';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import type { VxeTableInstance, VxeTablePropTypes, VxeTableEvents } from 'vxe-table';
import XEClipboard from 'xe-clipboard';
import VxePulldownSelectionWithNa from '@/components/VxePulldownSelectionWithNa.vue';
import { IsEmpty } from '@/utils/common';

/**全局变量定义区 ==========*/
let { proxy }: any = getCurrentInstance();
/**左侧表格 */
const loading = ref(false); /**刷新+表格加载*/
const form = reactive({ keyvalue: '' }); /**根据关键字查询*/
const tableRef = ref<VxeTableInstance<RowVO>>(); /**表格ref标记*/
const tableData = reactive([]); /**表格数据*/
let bacDrugResultTemplateObj: any = reactive({}); /**当前选中的药敏模板对象 */
let currentRow: any = reactive({ id: '', code: '' });
let curIndex = ref(-1);/**保存时记录当前选中索引，更换新完数据后 再次选中改行 */
/**右侧表单*/
const BacDrugResultTempdetailFormRef = ref<InstanceType<typeof BacDrugResultTempdetailForm>>();

/**vxe-table 表格右击属性*/
const menuConfig = reactive<VxeTablePropTypes.MenuConfig<RowVO>>({
  header: {
    options: [
      [
        { code: 'hideColumn', name: '隐藏列', disabled: false },
        { code: 'showAllColumn', name: '取消所有隐藏列', disabled: false }
      ]
    ]
  },
  body: {
    options: [
      [
        { code: 'copy', name: '复制', prefixIcon: 'vxe-icon-copy', disabled: false },
        { code: 'reload', name: '刷新', disabled: false },
        { code: 'remove', name: '删除', disabled: false },
        { code: 'save', name: '保存', prefixIcon: 'vxe-icon-save', disabled: false }
      ]
    ]
  },
  visibleMethod({ options, column }) {
    const isDisabled = !column;
    options.forEach((list) => {
      list.forEach((item) => {
        item.disabled = isDisabled;
      });
    });
    return true;
  }
});

defineExpose({
  tempSelectChange /**重置显示文本 */
});

/**方法定义区 =============*/
onMounted(() => {
  findList(); /**获取药敏模板明细表格数据*/
});

/**行切换事件 */
function tempSelectChange(row) {
  Object.assign(bacDrugResultTemplateObj, row);
  findList();
}

/**获取 药敏模板明细表格数据*/
const findList = () => {
  loading.value = true;
  tableData.length = 0; /**放入数据前清空数据*/
  const url = '/api/bac/bac-drug-result-tempdetail/findBacDrugResultTempdetailList';
  /**注意此处的数据条数*/
  const a = {
    keyWords: form.keyvalue, templdateNo: !IsEmpty(bacDrugResultTemplateObj) ? bacDrugResultTemplateObj.templateNo : '123!@#'
  };
  proxy.$http.get(url, { params: a })
    .then(async (res: any) => {
      tableData.push(...res.data);
      loading.value = false;
      if (res && res.data && res.data.length > 0) {
        const newSelRow = curIndex.value >= 0 && curIndex.value <= res.data.length - 1 ? res.data[curIndex.value] : res.data[0];
        tableCellClick({ row: newSelRow });
        const $table = tableRef.value;
        if ($table) {
          currentRow.id = '';
          await $table.setCurrentRow(newSelRow);
        }
      }
      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('获取药敏模板明细列表数据异常', VxeNotifyType.error);
    });
};

/**新增药敏模板明细*/
async function addBacDrugResultTempdetail() {
  tableRef.value?.clearCurrentRow();
  const row = {
    id: '',
    templdateId: bacDrugResultTemplateObj.id,
    templdateNo: bacDrugResultTemplateObj.templateNo,
    templdateNa: bacDrugResultTemplateObj.templateNa,
    antId: '',
    antNo: '',
    antNa: '',
    astTestMthDictId: '',
    astTestMthDictNo: '',
    astTestMthDictNa: '',
    antPropGroupDictId: '',
    antPropGroupDictNo: '',
    antPropGroupDictNa: '',
    breakPoint: '',
    r: '',
    i: '',
    sdd: '',
    ecoff: '',
    s: '',
    defResult: '',
    interCodeDictId: '',
    interCodeDictNo: '',
    interCodeDictNa: '',
    seq: tableData.length + 1 + ''
  };
  tableData.push(row);
  await tableRef.value?.setCurrentRow(row);
  await tableRef.value?.setEditCell(row, 'antNa');
}

/**保存药敏模板明细*/
function saveBacDrugResultTempdetail() {
  loading.value = true;
  const row = tableRef.value?.getCurrentRecord();
  curIndex.value = tableRef.value?.getRowIndex(row);
  proxy.$http
    .post('/api/bac/bac-drug-result-tempdetail/batchSaveBacDrugResultTempdetail', tableData)
    .then((res: any) => {
      if (res.status.code === 1) {
        VxeMessage(res.status.msg, VxeNotifyType.success);
        findList();
      } else {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      }
      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
    });
}

/**删除药敏模板明细*/
async function deleteBacDrugResultTempdetail() {
  const arr = await tableRef.value?.getCheckboxRecords(true);
  if (!(arr && arr.length > 0 && arr[0])) {
    VxeMessage('请勾选要删除的药敏模板明细', VxeNotifyType.info);
    return;
  } else if (arr.length > 1) {
    VxeMessage('一次只可选择删除一条数据', VxeNotifyType.info);
    return;
  } else {
    proxy
      .$confirm('确定删除选中数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        const url = '/api/bac/bac-drug-result-tempdetail/deleteBacDrugResultTempdetail';
        const arr = await tableRef.value?.getCheckboxRecords(true);
        if (arr && arr.length > 0 && arr[0]) {
          proxy.$http
            .post(url, arr[0])
            .then((res: any) => {
              if (res.status.code === 1) {
                VxeMessage('删除药敏模板明细成功', VxeNotifyType.success);
                findList();
                BacDrugResultTempdetailFormRef.value?.clearFormData();
              } else {
                VxeMessage('删除药敏模板明细失败', VxeNotifyType.error);
              }
            })
            .catch((err: any) => {
              // VxeMessage('删除药敏模板明细异常', VxeNotifyType.error);
            });
        }
      });
  }
}

// 表格右击菜单项
const contextMenuClickEvent: VxeTableEvents.MenuClick<RowVO> = ({ menu, row, column }) => {
  const $table = tableRef.value;
  if (table) {
    switch (menu.code) {
      case 'hideColumn':
        $table.hideColumn(column);
        break;
      case 'showAllColumn':
        $table.resetColumn(true);
        break;
      case 'copy':
        if (XEClipboard.copy((row as any)[column.field])) {
          VXETable.modal.message({ content: '已复制到剪贴板！', status: 'success' });
        }
        break;
      case 'reload':
        findList();
        break;
      case 'insertAt':
        $table.insertAt({}, row || -1).then(({ row }) => {
          $table.setEditCell(row, column || 'name');
        });
        break;
      case 'remove':
        $deleteBacDrugResultTempdetail();
        break;
      case 'save':
        saveBacDrugResultTempdetail();
        break;
    }
  }
};

/**表格选中当前行*/
function tableCellClick({ row }) {
  Object.assign(currentRow, row);
  proxy.$forceUpdate();
}
/**下拉选中行事件 */
function SelectRowClick(e) {
  e.aimKeys.forEach((r) => {
    tableData[e.childIndex][r.aimKey] = e.row[r.rowKey];
  });
}
</script>
<style lang="scss" scoped>
#BacDrugResultTempdetail {
  width: 100%;
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .splitpanes {
      background-color: $base-white;
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
    }
  }

  .panel-detail {
    background-color: $base-white;
  }

  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }

  .tableBox {
    height: calc(100% - 40px);
  }
}
</style>
